﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EAS_Protocol.WBXML;
using System.Xml.Linq;
using System.IO;

namespace EASWebAccess.Controllers
{
    /// <summary>
    /// Controller for handling WBXML
    /// </summary>
    public class WBXMLController : Controller
    {        
        /// <summary>
        /// Method for converting WBXML to POX
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ActionName("wbToXml")]
        public string wbToXml()
        {            
            byte[] xmlSource = this.Request.BinaryRead(this.Request.ContentLength);
            
            WBXMLWriter wbWriter = new WBXMLWriter(new ASCodePageProvider());
            WBXMLConverter wbConvert = new WBXMLConverter(new ASCodePageProvider(), wbWriter, null);
            XElement xmlResult = wbConvert.Parse(xmlSource);

            return xmlResult.ToString();
        }
        
        /// <summary>
        /// Method for converting POX to WBXML
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ActionName("xmlToWb")]
        public string xmlToWb()
        {            
            byte[] b = this.Request.BinaryRead(this.Request.ContentLength);            
            string xmlSource = System.Text.Encoding.UTF8.GetString(b);

            StringReader sr = new StringReader(xmlSource);

            XDocument xDoc = XDocument.Load(sr, LoadOptions.None);

            WBXMLWriter wbWriter = new WBXMLWriter(new ASCodePageProvider());
            WBXMLConverter wbConvert = new WBXMLConverter(new ASCodePageProvider(), wbWriter, null);

            IList<byte> wbXmlResult = wbConvert.Parse(xDoc);

            byte[] bytesArr = wbXmlResult.ToArray();

            return System.Text.Encoding.UTF8.GetString(bytesArr);
        }

    }
}
